<template>
  <view class="xen-audit-actions">
    <!-- 安全区域适配 -->
    <view class="actions-container" :style="containerStyle">
      <view class="actions-content">
        <!-- 主要操作按钮 -->
        <view class="primary-actions">
          <button
            v-for="action in visibleActions"
            :key="action.key"
            class="action-btn"
            :class="getButtonClass(action.type)"
            :style="action.customStyle"
            :disabled="action.disabled"
            @click="handleAction(action)"
          >
            <uni-icons
              v-if="action.icon"
              :type="action.icon"
              size="18"
              :color="getIconColor(action.type)"
            ></uni-icons>
            <text class="btn-text">{{ action.label }}</text>
          </button>
        </view>

        <!-- 更多操作按钮 -->
        <view v-if="hasMoreActions" class="more-actions">
          <button class="more-btn" @click="showMoreActions">
            <uni-icons type="more-filled" size="18" color="#666"></uni-icons>
          </button>
        </view>
      </view>
    </view>

    <!-- 更多操作弹窗遮罩 -->
    <view v-if="showMorePopup" class="popup-mask" @click="hideMoreActions">
      <!-- 更多操作弹窗 -->
      <view class="more-popup" @click.stop>
        <view class="popup-header">
          <text class="popup-title">更多操作</text>
          <view class="close-btn" @click="hideMoreActions">
            <uni-icons type="closeempty" size="20" color="#999"></uni-icons>
          </view>
        </view>
        <view class="popup-actions">
          <button
            v-for="action in moreActionsList"
            :key="action.key"
            class="popup-action-btn"
            :style="action.customStyle"
            :disabled="action.disabled"
            @click="handleAction(action)"
          >
            <uni-icons
              v-if="action.icon"
              :type="action.icon"
              size="20"
              :color="action.disabled ? '#ccc' : '#333'"
            ></uni-icons>
            <text class="popup-btn-text" :class="{ disabled: action.disabled }">
              {{ action.label }}
            </text>
          </button>
        </view>
      </view>
    </view>

    <!-- 审批原因输入弹窗 -->
    <XenFormPopup
      ref="approvalPopup"
      :title="approvalPopupTitle"
      :subtitle="approvalPopupSubtitle"
      :confirm-text="approvalPopupConfirmText"
      :loading="approvalLoading"
      loading-text="处理中..."
      @confirm="confirmApproval"
      @close="handleApprovalPopupClose"
    >
      <template #form>
        <view class="approval-form">
          <view class="form-item">
            <view class="form-label">
              审批原因
              <text v-if="requireApprovalReason" class="required">*</text>
            </view>
            <textarea
              v-model="approvalRemark"
              class="form-textarea"
              :placeholder="approvalPlaceholder"
              :maxlength="200"
              :auto-height="true"
              :show-confirm-bar="false"
            />
            <view class="char-count">{{ approvalRemark.length }}/200</view>
          </view>
        </view>
      </template>
    </XenFormPopup>
  </view>
</template>

<script setup lang="ts">
import { ref, computed } from "vue";
import XenFormPopup from "./XenFormPopup.vue";

// 定义操作类型
type ActionType = "primary" | "success" | "warning" | "danger" | "default";

// 定义操作接口
interface AuditAction {
  key: string;
  label: string;
  type: ActionType;
  icon?: string;
  disabled?: boolean;
  visible?: boolean;
  primary?: boolean; // 是否为主要操作，显示在主按钮区域
  customStyle?: string; // 自定义样式
}

// 组件属性
interface Props {
  actions?: AuditAction[];
  maxPrimaryActions?: number; // 主要操作区域最多显示的按钮数量
  safeAreaBottom?: boolean; // 是否适配底部安全区域
}

const props = withDefaults(defineProps<Props>(), {
  actions: () => [],
  maxPrimaryActions: 2,
  safeAreaBottom: true,
});

// 事件定义
const emit = defineEmits<{
  (e: "action", action: AuditAction, remark?: string): void;
}>();

// 更多操作弹窗显示状态
const showMorePopup = ref(false);

// 审批原因对话框状态
const approvalPopup = ref();
const approvalRemark = ref("");
const approvalLoading = ref(false);
const pendingApprovalAction = ref<AuditAction | null>(null);

// 审批弹窗的动态配置
const approvalPopupTitle = ref("");
const approvalPopupSubtitle = ref("");
const approvalPopupConfirmText = ref("");
const approvalPlaceholder = ref("");
const requireApprovalReason = ref(true); // 是否必填审批原因

// 默认操作列表（静态版本）
const defaultActions: AuditAction[] = [
  {
    key: "approve",
    label: "通过",
    type: "success",
    icon: "checkmarkempty",
    primary: true,
  },
  {
    key: "reject",
    label: "拒绝",
    type: "danger",
    icon: "closeempty",
    primary: true,
  },
  {
    key: "return",
    label: "退回",
    type: "warning",
    icon: "undo",
  },
  {
    key: "transfer",
    label: "转办",
    type: "default",
    icon: "forward",
  },
  {
    key: "comment",
    label: "添加备注",
    type: "default",
    icon: "compose",
  },
];

// 计算实际使用的操作列表
const actionsList = computed(() => {
  const actions = props.actions.length > 0 ? props.actions : defaultActions;
  return actions.filter((action) => action.visible !== false);
});

// 计算主要操作
const visibleActions = computed(() => {
  const primaryActions = actionsList.value.filter((action) => action.primary);
  return primaryActions.slice(0, props.maxPrimaryActions);
});

// 计算更多操作
const moreActionsList = computed(() => {
  const primaryKeys = visibleActions.value.map((action) => action.key);
  return actionsList.value.filter(
    (action) => !primaryKeys.includes(action.key),
  );
});

// 是否有更多操作
const hasMoreActions = computed(() => {
  return moreActionsList.value.length > 0;
});

// 容器样式
const containerStyle = computed(() => {
  const styles: Record<string, string> = {};

  if (props.safeAreaBottom) {
    // 获取底部安全区域高度
    const systemInfo = uni.getSystemInfoSync();
    const safeAreaBottom = systemInfo.safeAreaInsets?.bottom || 0;
    // 为安卓端增加额外的底部间距，确保不贴边
    const extraBottomPadding = 8; // 额外增加8px底部间距
    styles.paddingBottom = `${safeAreaBottom + extraBottomPadding}px`;
  }

  return styles;
});

// 获取按钮样式类
const getButtonClass = (type: ActionType): string => {
  return `action-btn--${type}`;
};

// 获取图标颜色
const getIconColor = (type: ActionType): string => {
  const colorMap: Record<ActionType, string> = {
    primary: "#ffffff",
    success: "#ffffff",
    warning: "#ffffff",
    danger: "#ffffff",
    default: "#666666",
  };
  return colorMap[type] || "#666666";
};

// 处理操作点击
const handleAction = (action: AuditAction) => {
  if (action.disabled) return;

  // 如果是从更多操作弹窗点击的，先关闭弹窗
  if (showMorePopup.value) {
    showMorePopup.value = false;
  }

  // 如果是同意操作，显示审批原因输入对话框
  if (action.key === "approve") {
    pendingApprovalAction.value = action;
    approvalRemark.value = "";
    // 配置同意操作的弹窗
    approvalPopupTitle.value = "审批原因";
    approvalPopupSubtitle.value = "请填写审批原因";
    approvalPopupConfirmText.value = "确认同意";
    approvalPlaceholder.value = "请详细说明审批原因...";
    requireApprovalReason.value = false; // 同意操作不强制要求填写原因
    approvalPopup.value?.open();
    return;
  }

  // 如果是拒绝操作，显示审批原因输入对话框
  if (action.key === "reject") {
    pendingApprovalAction.value = action;
    approvalRemark.value = "";
    // 配置拒绝操作的弹窗
    approvalPopupTitle.value = "审批原因";
    approvalPopupSubtitle.value = "请填写审批原因";
    approvalPopupConfirmText.value = "确认拒绝";
    approvalPlaceholder.value = "请详细说明审批原因...";
    requireApprovalReason.value = true; // 拒绝操作强制要求填写原因
    approvalPopup.value?.open();
    return;
  }

  emit("action", action);
};

// 显示更多操作
const showMoreActions = () => {
  showMorePopup.value = true;
};

// 隐藏更多操作
const hideMoreActions = () => {
  showMorePopup.value = false;
};

// 隐藏审批原因对话框
const hideApprovalDialog = () => {
  approvalRemark.value = "";
  pendingApprovalAction.value = null;
  approvalLoading.value = false;
};

// 处理审批弹窗关闭事件
const handleApprovalPopupClose = () => {
  hideApprovalDialog();
};

// 确认审批操作
const confirmApproval = () => {
  // 如果是拒绝操作且需要填写原因，进行校验
  if (requireApprovalReason.value && !approvalRemark.value.trim()) {
    uni.showToast({
      title: "请填写审批原因",
      icon: "none",
    });
    return;
  }

  if (pendingApprovalAction.value) {
    approvalLoading.value = true;
    emit("action", pendingApprovalAction.value, approvalRemark.value.trim());
    // 注意：这里不立即关闭弹窗，让父组件处理完成后再关闭
  }
};

// 关闭审批弹窗（供外部调用）
const closeApprovalPopup = () => {
  approvalPopup.value?.close();
};

// 暴露方法给父组件
defineExpose({
  closeApprovalPopup,
  // 为了向后兼容，保留旧的方法名
  closeRejectPopup: closeApprovalPopup,
});
</script>

<style lang="scss" scoped>
.xen-audit-actions {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  z-index: 999;
}

.actions-container {
  background-color: #ffffff;
  border-top: 1px solid #f0f0f0;
  box-shadow: 0 -4px 16px rgba(0, 0, 0, 0.1);
  padding: 8px 16px;
}

.actions-content {
  display: flex;
  align-items: center;
  gap: 12px;
}

.primary-actions {
  flex: 1;
  display: flex;
  gap: 12px;
}

.action-btn {
  flex: 1;
  height: 44px;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 6px;
  font-size: 15px;
  font-weight: 500;
  border: none;
  transition: all 0.2s;

  &:active {
    opacity: 0.8;
  }

  &[disabled] {
    opacity: 0.5;
  }

  &--primary {
    background: linear-gradient(135deg, #7579f5 0%, #9973f8 100%);
    color: #ffffff;
    box-shadow: 0 2px 8px rgba(107, 114, 242, 0.3);
  }

  &--success {
    background: linear-gradient(135deg, #52c41a 0%, #73d13d 100%);
    color: #ffffff;
    box-shadow: 0 2px 8px rgba(82, 196, 26, 0.3);
  }

  &--warning {
    background: linear-gradient(135deg, #faad14 0%, #ffc53d 100%);
    color: #ffffff;
    box-shadow: 0 2px 8px rgba(250, 173, 20, 0.3);
  }

  &--danger {
    background: linear-gradient(135deg, #f5222d 0%, #ff4d4f 100%);
    color: #ffffff;
    box-shadow: 0 2px 8px rgba(245, 34, 45, 0.3);
  }

  &--default {
    background: #f0f0f0;
    color: #666;
  }
}

.btn-text {
  font-size: 15px;
}

.more-actions {
  .more-btn {
    width: 44px;
    height: 44px;
    border-radius: 8px;
    background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
    color: #495057;
    border: 1px solid #dee2e6;
    display: flex;
    align-items: center;
    justify-content: center;
    transition: all 0.2s;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
    position: relative;
    overflow: hidden;

    // 添加微妙的光泽效果
    &::before {
      content: "";
      position: absolute;
      top: 0;
      left: -100%;
      width: 100%;
      height: 100%;
      background: linear-gradient(
        90deg,
        transparent,
        rgba(255, 255, 255, 0.4),
        transparent
      );
      transition: left 0.5s;
    }

    &:active {
      opacity: 0.8;
      transform: scale(0.98);
      box-shadow: 0 1px 2px rgba(0, 0, 0, 0.15);

      &::before {
        left: 100%;
      }
    }

    // 悬停效果（在支持的平台上）
    &:hover {
      background: linear-gradient(135deg, #e9ecef 0%, #dee2e6 100%);
      border-color: #adb5bd;
      box-shadow: 0 2px 6px rgba(0, 0, 0, 0.15);

      &::before {
        left: 100%;
      }
    }
  }
}

// 更多操作弹窗样式
.popup-mask {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  z-index: 1000;
  display: flex;
  align-items: flex-end;
  justify-content: center;
}

.more-popup {
  background-color: #ffffff;
  border-radius: 16px 16px 0 0;
  max-height: 60vh;
  width: 100%;
  animation: slideUp 0.3s ease-out;
}

@keyframes slideUp {
  from {
    transform: translateY(100%);
  }
  to {
    transform: translateY(0);
  }
}

.popup-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px 24px;
  border-bottom: 1px solid #f0f0f0;

  .popup-title {
    font-size: 16px;
    font-weight: 500;
    color: #333;
  }

  .close-btn {
    width: 32px;
    height: 32px;
    display: flex;
    align-items: center;
    justify-content: center;
    border-radius: 16px;
    background-color: #f5f5f5;

    &:active {
      background-color: #e6e6e6;
    }
  }
}

.popup-actions {
  padding: 16px 24px 24px;
}

.popup-action-btn {
  width: 100%;
  height: 48px;
  background-color: #ffffff;
  border: 1px solid #f0f0f0;
  border-radius: 8px;
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 0 16px;
  margin-bottom: 12px;
  transition: all 0.2s;

  &:last-child {
    margin-bottom: 0;
  }

  &:active:not([disabled]) {
    opacity: 0.8;
    background-color: #f5f5f5;
  }

  &[disabled] {
    opacity: 0.5;
  }
}

.popup-btn-text {
  font-size: 15px;
  color: #333;
  font-weight: 500;

  &.disabled {
    color: #ccc;
  }
}

// 审批表单样式
.approval-form {
  .form-item {
    margin-bottom: 24rpx;

    .form-label {
      font-size: 28rpx;
      color: #2c3e50;
      margin-bottom: 16rpx;
      font-weight: 500;
      display: block;

      .required {
        color: #f56c6c;
        margin-left: 4rpx;
      }
    }

    .form-textarea {
      width: 100%;
      min-height: 200rpx;
      padding: 24rpx;
      border: 2rpx solid #e4e7ed;
      border-radius: 12rpx;
      font-size: 28rpx;
      color: #2c3e50;
      background-color: #fafbfc;
      resize: none;
      box-sizing: border-box;
      line-height: 1.5;

      &:focus {
        border-color: #3c9cff;
        background-color: #ffffff;
        box-shadow: 0 0 0 4rpx rgba(60, 156, 255, 0.1);
      }

      &::placeholder {
        color: #8f9bb3;
      }
    }

    .char-count {
      text-align: right;
      font-size: 24rpx;
      color: #8f9bb3;
      margin-top: 12rpx;
    }
  }
}
</style>
